const { NAME_OR_PASSWORD_IS_REQUEIRED, NAME_IS_NOT_EXIT, PASSWORD_IS_INCORRECT, UNAUTHPRIZATION } = require("../config/error")
const { PUBLIC_KEY } = require("../config/screct")
const userService = require("../service/user.service")
const md5password = require("../utils/md5-password")
const jwt = require('jsonwebtoken')

const verifLogin = async (ctx, next) => {
    const { name, password } = ctx.request.body
    // console.log(name, password)
    // 1.判断账号密码是否为空
    if (!password || !name) {
        return ctx.app.emit('error', NAME_OR_PASSWORD_IS_REQUEIRED)
    }
    // 2.查询用户在数据库是否存在
    const users = await userService.findUserByName(name)
    const user = users[0]
    // console.log(user)
    if (!user) {
        return ctx.app.emit('error', NAME_IS_NOT_EXIT, ctx)
    }
    // 3.查询密码和数据库的是否一致
    if (user.password != md5password(password)) {
        // console.log('错误')
        return ctx.app.emit('error', PASSWORD_IS_INCORRECT, ctx)
    }
    // 4，将user保存在ctx
    ctx.user = user
    // console.log(ctx.user)
    await next()
}
const verifAuth = async (ctx, next) => {
    // 1.获取token
    const authorization = ctx.headers.authorization
    if (!authorization) {
        return ctx.app.emit('error', UNAUTHPRIZATION, ctx)
    }
    const token = authorization.replace('Bearer ', '')//注意Bearer后面有一个空格
    // console.log(token)
    // console.log('123')
    // 2，验证token是否有效
    try {
        const result = jwt.verify(token, PUBLIC_KEY, {
            algorithms: ['RS256']
        })
        // 2.1将token信息保存下来
        ctx.user = result
        // console.log(result)
        // 3.执行下一个中间件
        await next()
    } catch (error) {
        console.log(error)
        ctx.app.emit('error', UNAUTHPRIZATION, ctx)
    }
}
module.exports = { verifLogin, verifAuth }